//
//  PIDrawerViewController.m
//  PIImageDoodler
//
//  Created by Pavan Itagi on 07/03/14.
//  Copyright (c) 2014 Pavan Itagi. All rights reserved.
//

#import "PIDrawerViewController.h"
#import "PIDrawerView.h"
#import "PIColorPickerController.h"
#import <MobileCoreServices/MobileCoreServices.h>

#import "TSAssetsPickerController.h"

#import "DummyAssetsImporter.h"
#import "DummyAlbumCell.h"
#import "DummyNoAlbumsCell.h"
#import "DummyAlbumsTableView.h"
#import "DummyAssetCell.h"
#import "DummyAssetsCollectionView.h"
#import "AssetsCollectionViewLayout.h"
#import "DeviceTypesMacros.h"
#import "DWBubbleMenuButton.h"

@interface PIDrawerViewController () <UIImagePickerControllerDelegate, UIActionSheetDelegate, UINavigationControllerDelegate, PIColorPickerControllerDelegate,TSAssetsPickerControllerDelegate, TSAssetsPickerControllerDataSource, UINavigationControllerDelegate,DWBubbleMenuViewDelegate>
{
    TSAssetsPickerController *_picker;
    IBOutlet UIButton *homeButton;
    UILabel  *functionLabel;
    DWBubbleMenuButton *downMenuButton ;
    IBOutlet PIDrawerView *container;
}
@property (weak, nonatomic) IBOutlet PIDrawerView *drawerView;
@property (weak, nonatomic) IBOutlet UIImageView *backGroundImageView;
@property (weak, nonatomic) IBOutlet UIButton *pickImageButton;
@property (weak, nonatomic) IBOutlet UIButton *pickColorButton;
@property (weak, nonatomic) IBOutlet UIButton *pickEraserButton;
@property (weak, nonatomic) IBOutlet UIButton *writeButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;

@property (nonatomic, strong) UIColor *selectedColor;
@property (nonatomic, strong) UIImage *currentImage;
@property (nonatomic, strong) NSMutableArray *images;
@property (nonatomic, assign) NSUInteger currentIndex;

- (IBAction)pickImageButtonPressed:(id)sender;
- (IBAction)pickColorButtonPressed:(id)sender;
- (IBAction)pickEraserButtonPressed:(id)sender;
- (IBAction)saveButtonPressed:(id)sender;
- (IBAction)writeButtonPressed:(id)sender;
@end

@interface UIImagePickerController (LandScapeImagePicker)

- (BOOL)shouldAutorotate;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation ;

-(NSUInteger)supportedInterfaceOrientations ;

@end

@implementation UIImagePickerController (LandScapeImagePicker)

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
//    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight||
//        toInterfaceOrientation ==
//        UIDeviceOrientationPortrait||
//        toInterfaceOrientation ==
//        UIDeviceOrientationPortraitUpsideDown) {
//        return YES;
//    }
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        return YES;
    }
    return NO;
}


- (BOOL)shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

@end

@implementation PIDrawerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNavTitle:@"选择图片"];
    
    [self setNavBackButton:nil];
    [self setNavRightButton:@"关闭"];
    
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    [self.pickColorButton.layer setBorderColor:[UIColor blackColor].CGColor];
    [self.pickColorButton.layer setBorderWidth:5.0];
    [self.pickColorButton.layer setCornerRadius:3.0];
    
    self.selectedColor = [UIColor redColor];
    [self.pickColorButton setBackgroundColor:self.selectedColor];
    [self.drawerView setSelectedColor:self.selectedColor];
    
    if (self.imageEdit) {
        self.currentImage = self.imageEdit;
        self.drawerView.viewImage = self.imageEdit;
    }
    
    [self writeButtonPressed:nil];
    
    
    functionLabel = [self createHomeButtonView];
    
    downMenuButton = [[DWBubbleMenuButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width- 50.f-90.f,
                                                                                              self.view.frame.size.height-50.f-120.f,
                                                                                              90,
                                                                                              90)
                                                                expansionDirection:DirectionLeft];
    downMenuButton.delegate = self;
    downMenuButton.homeButtonView = functionLabel;
    
    [downMenuButton addButtons:[self createDemoButtonArray]];
    
    [self.view addSubview:downMenuButton];
    
    [self performSelector:@selector(showfuction) withObject:nil afterDelay:.8f];
}

-(void)showfuction
{
    [downMenuButton showButtons];
}

//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    //kbSize即為鍵盤尺寸 (有width, height)
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度
    NSLog(@"hight_hitht:%f",kbSize.height);
    
    float height = self.drawerView.txtView.frame.size.height + self.drawerView.txtView.frame.origin.y + 44 + 20;
    
    float beyondH = [UIApplication sharedApplication].keyWindow.frame.size.height-height-kbSize.height;
    
    if (beyondH < 0) {
        if (beyondH < (-1) * kbSize.height) {
            container.transform = CGAffineTransformMakeTranslation(0,(-1) * kbSize.height);
        }
        else
        {
            container.transform = CGAffineTransformMakeTranslation(0,beyondH);
        }
//        container.transform = CGAffineTransformMakeTranslation(0,beyondH);
    }
    
//    if(kbSize.height == 216)
//    {
//        keyboardhight = 0;
//    }
//    else
//    {
//        keyboardhight = 36;   //252 - 216 系统键盘的两个不同高度
//    }
//    //输入框位置动画加载
//    [self begainMoveUpAnimation:keyboardhight];
}

//当键盘隐藏的时候
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    //do something
//    [UIView animateWithDuration:.8f animations:^{
        container.transform = CGAffineTransformIdentity;
//    }];
}

- (void)navRightButtonActionAtTag:(NSUInteger)tag
{
    //todo:返回数据
    [super backAction:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UILabel *)createHomeButtonView {
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.f, 0.f, 90.f, 90.f)];
    label.text = @"功能";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont boldSystemFontOfSize:18.0];
    label.textAlignment = NSTextAlignmentCenter;
    label.layer.cornerRadius = label.frame.size.height / 2.f;
    label.backgroundColor =[UIColor colorWithRed:.0f green:0.2f blue:1.f alpha:0.5f];
    label.clipsToBounds = YES;
    
    return label;
}

- (NSArray *)createDemoButtonArray {
    
    NSMutableArray *buttonsMutable = [[NSMutableArray alloc] init];
    
    int i = 0;
    for (NSString *title in @[@"选择照片",@"文本框",@"保存备注", @"画笔", @"颜料桶", @"撤销", @"保存照片"]) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitle:title forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont boldSystemFontOfSize:17.0];
        button.frame = CGRectMake(0.f, 0.f, 70.f, 70.f);
        button.layer.cornerRadius = button.frame.size.height / 2.f;
        button.backgroundColor = [UIColor colorWithRed:1.f green:0.f blue:0.f alpha:0.5f];
        button.clipsToBounds = YES;
        button.tag = i++;
        
        [button addTarget:self action:@selector(functionAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [buttonsMutable addObject:button];
    }
    
    return [buttonsMutable copy];
}

#pragma mark -bubbleMunu delegate
- (void)bubbleMenuButtonWillExpand:(DWBubbleMenuButton *)expandableView
{
    functionLabel.text = @"< 功能";
}
- (void)bubbleMenuButtonWillCollapse:(DWBubbleMenuButton *)expandableView
{
    functionLabel.text = @"功能";
}

-(void)functionAction:(id)sender
{
    UIButton *btn = (UIButton*)sender;
    if ([btn.titleLabel.text isEqualToString:@"选择照片"]) {
        
        [self pickImageButtonPressed:btn];
    }else if ([btn.titleLabel.text isEqualToString:@"文本框"])
    {
        [self addTxtPressed:btn];
        
    }else if ([btn.titleLabel.text isEqualToString:@"保存备注"])
    {
        [self drawString];
        
    }else if ([btn.titleLabel.text isEqualToString:@"画笔"])
    {
        [self writeButtonPressed:btn];
        
    }else if ([btn.titleLabel.text isEqualToString:@"颜料桶"])
    {
        [self pickColorButtonPressed:btn];
    }
    else if ([btn.titleLabel.text isEqualToString:@"撤销"])
    {
        [self pickEraserButtonPressed:btn];
    }
    else if ([btn.titleLabel.text isEqualToString:@"保存照片"])
    {
        [self saveButtonPressed:btn];
    }
}

#pragma mark - Button Action methods
- (IBAction)pickImageButtonPressed:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",@"拍照",nil];
    [actionSheet showInView:self.view];
}

- (IBAction)pickColorButtonPressed:(id)sender
{
    PIColorPickerController *colorPicker = [[PIColorPickerController alloc] initWithNibName:@"PIColorPickerController" bundle:nil];
    [colorPicker setDelegate:self];
    [colorPicker setCurrentSelectedColor:self.selectedColor];
    [self presentViewControllerInSmallRect:colorPicker];
}

- (IBAction)pickEraserButtonPressed:(id)sender
{
//    [self.drawerView setDrawingMode:DrawingModeErase];
    
    if (self.drawerView.txtView) {
        [self.drawerView.txtView removeFromSuperview];
    }
    
    self.drawerView.viewImage = self.currentImage;
    
    [self.drawerView setNeedsDisplay];
}

//保存备注到图片
- (IBAction)drawString
{
    UIGraphicsBeginImageContext(self.drawerView.bounds.size);
    [self.drawerView.viewImage drawInRect:self.drawerView.bounds];
    
    [self.selectedColor set];
    
    NSString *msg = self.drawerView.txtView.text;
    
    UIFont *font = [UIFont fontWithName:@"Courier" size:25];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:self.drawerView.txtView.frame];
    
    lab.numberOfLines=0;
    
    lab.font = font;
    
    lab.text = msg;
    
    [lab sizeToFit];
    
    [self.drawerView.txtView removeFromSuperview];
    
    // 绘制矩形
    // 1.获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 2.绘图
    CGContextAddRect(ctx, lab.frame);
    // 3.渲染
    CGContextStrokePath(ctx);
    
    /// Make a copy of the default paragraph style
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    /// Set line break mode
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    /// Set text alignment
    paragraphStyle.alignment = NSTextAlignmentLeft;
    
    NSDictionary *attributes = @{ NSFontAttributeName: font,
                                  NSForegroundColorAttributeName: self.selectedColor,
                                  NSParagraphStyleAttributeName: paragraphStyle };
    
//    [text drawInRect:rect withAttributes:attributes];
    

    
    [msg drawInRect:lab.frame withAttributes:attributes];
    
    self.drawerView.viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [self.drawerView setNeedsDisplay];
}

- (IBAction)saveButtonPressed:(id)sender
{
    if (self.drawerView.viewImage) {
        UIImage *image = self.drawerView.viewImage;
        
//        NSData *data;
//        
//        NSLog(@"%lu",(unsigned long)data.length);
//        
//        if (UIImagePNGRepresentation(image) == nil) {
//            
//            data = UIImageJPEGRepresentation(image, 1);
//            
//        } else {
//            
//            data = UIImagePNGRepresentation(image);
//        }
        
        [self saveImageToPhotos:image];
    }
    else
    {
        [gAlert show:@"还没有选择照片哦" inView:self.view delegate:nil];
    }
    
    
//    NSLog(@"%@",data);
    
//    UIImage *changeImage = [UIImage imageWithData: data];
//    
//    UIImageView *changedImgV=[[UIImageView alloc] initWithImage:changeImage];
//    
//    UIView *bg=[[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    
//    bg.backgroundColor=[UIColor whiteColor];
//    
//    changedImgV.frame=[UIScreen mainScreen].bounds;
//    
//    [bg addSubview:changedImgV];
//    
//    [[UIApplication sharedApplication].keyWindow addSubview:bg];
}

- (void)saveImageToPhotos:(UIImage*)savedImage
{    
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    
    NSMutableArray *arr = [NSMutableArray array];
    [arr addObject:savedImage];
    
    if (self.addImages) {
        self.addImages(arr);
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

// 指定回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
//    NSString *msg = nil ;
//
//    if(error != NULL){
//        msg = @"保存图片失败" ;
//    }else{
//        msg = @"保存图片成功" ;
//    }
//
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
//                                                    message:msg
//                                                   delegate:self
//                                          cancelButtonTitle:@"确定"
//                                          otherButtonTitles:nil];
//    [alert show];
}

- (IBAction)addTxtPressed:(id)sender
{
    [self.drawerView setDrawingMode:DrawingModeTxt];
    self.drawerView.color = self.selectedColor;
}

- (IBAction)writeButtonPressed:(id)sender
{
    [self.drawerView setDrawingMode:DrawingModePaint];
}

#pragma mark - UIActionSheetDelegate methods
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
        mediaUI.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//UIImagePickerControllerSourceTypeCamera
//        mediaUI.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeSavedPhotosAlbum];
        mediaUI.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        mediaUI.allowsEditing = NO;
        mediaUI.delegate = self;
//        [mediaUI shouldAutorotate];
        
//        UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:mediaUI];
//        
//        popover.popoverContentSize = mediaUI.contentSizeForViewInPopover;
//        
//        if (mediaUI.sourceType==UIImagePickerControllerSourceTypeCamera
//            
//            && (UIDeviceOrientationIsLandscape([[UIDevice currentDevice]orientation]))) {
//            
//            
//            
//            mediaUI.cameraViewTransform = CGAffineTransformMakeRotation(M_PI/2);
//            
//            
//            
//        }
//        
//        [popover presentPopoverFromRect: CGRectMake(0, 0, 1024, 0)
//         
//                                 inView:self.view
//         
//               permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        
        [self presentViewController:mediaUI animated:YES completion:nil];
        
//        if (!_picker) {
//            _picker = [TSAssetsPickerController new];
//            _picker.delegate = self;
//            _picker.dataSource = self;
//        }
//        
//        //        [self.navigationController pushViewController:_picker animated:YES];
//        
//        //        self.view.window.rootViewController=_picker;
//        
//        [self presentViewController:_picker animated:YES completion:nil];//弹出从相册多选页面
    }
    else if(buttonIndex == 1)
    {
        //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        //    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        //        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //    }
        //sourceType = UIImagePickerControllerSourceTypeCamera; //照相机
        //sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
        //sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; //保存的相片
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = sourceType;
//        [picker shouldAutorotate];
        [self presentViewController:picker animated:YES completion:nil];
        //        [self.navigationController pushViewController:picker animated:YES];//进入照相界面
    }
}

//- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (buttonIndex == 0) {
////        UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
////        mediaUI.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//UIImagePickerControllerSourceTypeCamera
////        mediaUI.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeSavedPhotosAlbum];
////        mediaUI.allowsEditing = NO;
////        mediaUI.delegate = self;
////        [self presentViewController:mediaUI animated:YES completion:nil];
//        
//        if (!_picker) {
//            _picker = [TSAssetsPickerController new];
//            _picker.delegate = self;
//            _picker.dataSource = self;
//        }
//        
////        [self.navigationController pushViewController:_picker animated:YES];
//        
////        self.view.window.rootViewController=_picker;
//        
//        [self presentViewController:_picker animated:YES completion:nil];
//    }
//    else
//    {
//        //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
//        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
//        //    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
//        //        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        //    }
//        //sourceType = UIImagePickerControllerSourceTypeCamera; //照相机
//        //sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
//        //sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; //保存的相片
//        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
//        picker.delegate = self;
//        picker.allowsEditing = YES;//设置可编辑
//        picker.sourceType = sourceType;
//        
//        [self presentViewController:picker animated:YES completion:nil];
////        [self.navigationController pushViewController:picker animated:YES];//进入照相界面
//    }
//}

#pragma mark - UIImagePickerControllerDelegate methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = nil;
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    else
    {
        NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
        if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo)
        {
            image = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
        }
    }
    
    self.currentImage = image;
    
    self.drawerView.viewImage = image;
    
//    UIGraphicsBeginImageContext(self.drawerView.bounds.size);
//    [self.drawerView.viewImage drawInRect:self.drawerView.bounds];
    
    [self.drawerView setNeedsDisplay];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - PIColorPickerControllerDelegate methods
- (void)colorSelected:(UIColor *)selectedColor
{
    self.selectedColor = selectedColor;
    [self.pickColorButton setBackgroundColor:selectedColor];    
    [self.drawerView setSelectedColor:selectedColor];
    self.drawerView.color = selectedColor;
}

//多选照片
#pragma mark - TSAssetsPickerControllerDataSource
- (NSUInteger)numberOfItemsToSelectInAssetsPickerController:(TSAssetsPickerController *)picker {
    return 10;
}

- (TSFilter *)filterOfAssetsPickerController:(TSAssetsPickerController *)picker {
    return [TSFilter filterWithType:FilterTypeAll];
}

#pragma mark - TSAssetsPickerControllerDelegate
- (void)assetsPickerControllerDidCancel:(TSAssetsPickerController *)picker {
    [_picker dismissViewControllerAnimated:YES completion:nil];
}

//从相册选择照片结束回调
- (void)assetsPickerController:(TSAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets {
    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [_picker dismissViewControllerAnimated:YES completion:nil];
        self.images = [DummyAssetsImporter importAssets:assets];//处理选中照片
//        for (int i=0; i<self.images.count; i++) {
//            
//            UIImageView *imgview = [[UIImageView alloc] initWithImage:[self.images objectAtIndex:i]];
//            imgview.frame = CGRectMake(_scrollview.frame.size.height*i +10*(i+1), 0, _scrollview.frame.size.height, _scrollview.frame.size.height);
//            imgview.userInteractionEnabled = YES;
//            UITapGestureRecognizer* singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageSingleTap:)];
//            //点击的次数
//            singleRecognizer.numberOfTapsRequired = 1; // 单击
//            singleRecognizer.numberOfTouchesRequired = 1; //手指数
//            [imgview addGestureRecognizer:singleRecognizer];
//
//            imgview.tag = i;
//            [_scrollview addSubview:imgview];
//        }
//        _scrollview.contentSize = CGSizeMake(_scrollview.frame.size.height*self.images.count +10*(self.images.count+1), _scrollview.frame.size.height);


        self.currentImage = [self.images objectAtIndex:0];
        
        self.drawerView.viewImage = [self.images objectAtIndex:0];
        
        [self.drawerView setNeedsDisplay];
    });
}

-(void)imageSingleTap:(UITapGestureRecognizer*)gesture
{
    
    UIImageView *imageview = (UIImageView*)gesture.view;
    
    
    self.currentImage = imageview.image;
    
    self.drawerView.viewImage = imageview.image;
    
    [self.drawerView setNeedsDisplay];
}

- (void)assetsPickerController:(TSAssetsPickerController *)picker failedWithError:(NSError *)error {
    if (error) {
        NSLog(@"Error occurs. Show dialog or something. Probably because user blocked access to Camera Roll.");
    }
}

@end
